/*用户中心*/
"use client"
import React, { useEffect, useState } from "react"
import {
  Avatar, BreadcrumbItem, Breadcrumbs,
  Button,
  Card,
  Chip,
  Code,
  Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader,
  Spinner, Switch,
  Table,
  TableBody, TableCell,
  TableColumn,
  TableHeader,
  TableRow, useDisclosure
} from "@nextui-org/react"
import FolderService from "@/app/service/folderService"
import NoteService from "@/app/service/noteService"
import { useAsyncList } from "@react-stately/data"
import { AiFillHome } from "react-icons/ai"
import { CardBody } from "@nextui-org/card"
import { BiDotsVerticalRounded, BiFolderOpen, BiPlus } from "react-icons/bi"
import { useLocation, useSearchParams } from "react-router-dom"
import NoteEdit from "@/app/components/profile/note/noteEdit"
import ToastUtil from "@/app/utils/toastUtil"
import CreateFolder from "@/app/components/profile/folder/createFolder"
import CreateNote from "@/app/components/profile/note/createNote"
import { delay } from "framer-motion"
import DelNoteService from "@/app/service/components/delNoteService"
import DelFolderService from "@/app/service/components/delFolderService"
import CreateShareService from "@/app/service/components/createShareService"
import ShareModifyService from "@/app/service/shareModifyService"

/**
 * 个人中心文件夹列表和笔记列表渲染页
 * @constructor
 */
export default function Profile() {
  //第一种方式 ---> 会更新当前状态 所以不能返回上一个状态
  // const [path, setPath] = useState(params.path);
  //第二种方式 ---> 会更新URL参数 可以返回上一个状态
  const [search, setSearch] = useSearchParams()
  /*存储路由*/
  const [path, setPath] = useState(["/"])
  //状态定义
  const location = useLocation()
  const [isLoadingFolder, setIsLoadingFolder] = useState(true)
  const [isLoadingNote, setIsLoadingNote] = useState(true)
  const { isOpen, onOpen, onClose, onOpenChange } = useDisclosure()
  //创建文件夹Modal状态
  const { isOpen: isOpenFolder, onOpen: onOpenFolder, onOpenChange: onOpenChangeFolder } = useDisclosure()
  //创建笔记Modal状态
  const { isOpen: isOpenNote, onOpen: onOpenNote, onOpenChange: onOpenChangeNote } = useDisclosure()
  /*确认删除Modal状态*/
  const { isOpen: isOpenDelNote, onOpen: onOpenDelNote, onOpenChange: onOpenChangeDelNote } = useDisclosure()
  /*确认删除Modal状态*/
  const { isOpen: isOpenDelFolder, onOpen: onOpenDelFolder, onOpenChange: onOpenChangeDelFolder } = useDisclosure()
  /*创建分享状态*/
  const { isOpen: isOpenShare, onOpen: onOpenShare, onOpenChange: onOpenChangeShare } = useDisclosure()
  /*笔记Id临存*/
  const [noteId, setNoteId] = useState("")
  /*删除的笔记id和title*/
  const [delData, setDelData] = useState("")

  /*规则化输出数据*/
  const renderCell = React.useCallback((List: any, columnKey: any, isFolder: boolean) => {
        const cellValue = List[columnKey]
        if (isFolder) {
          switch (columnKey) {
            case "num":
              return (
                <Avatar isBordered color={"primary"} radius={"lg"} name={List.title.substring(0, 1)} />
              )
            case "id":
              return (
                <Chip className={"capitalize"} color={"primary"} variant={"flat"}
                      size={"sm"}>&nbsp;{List.id}&nbsp;</Chip>
              )
            case "createTime":
              return (
                <Chip color="primary" variant="dot" size={"sm"}>{List.createTime}</Chip>
              )
            case "status":
              return (
                <Switch isSelected={false} color="default" size={"sm"} onValueChange={() => {
                  ToastUtil("不支持分享目录", "❎", "error")
                }} />
              )
            case "title":
              return (
                <h6 className={"truncate font-medium text-base"}>{List.title}</h6>
              )
            case "content":
              return (
                <h6 className={"line-clamp-3 overflow-hidden"}>{List.content}</h6>
              )
            case "actions":
              return (
                <div className="relative flex justify-center items-end gap-2">
                  <Dropdown backdrop={"blur"} className="bg-background border-1 border-default-200">
                    <DropdownTrigger>
                      <Button isIconOnly radius="full" size="sm" variant="light">
                        <BiDotsVerticalRounded className="text-default-400" />
                      </Button>
                    </DropdownTrigger>
                    <DropdownMenu onAction={(key) => {
                      setDelData(key.toString())
                      onOpenDelFolder()
                    }}>
                      <DropdownItem color={"danger"} key={List.id}>删 除</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </div>
              )
            default:
              return cellValue
          }
        } else {
          switch (columnKey) {
            case "num":
              return (
                <Avatar isBordered color={"secondary"} radius={"lg"} name={List.title.substring(0, 1)} />
              )
            case "id":
              return (
                <Chip className={"capitalize"} variant={"flat"} size={"sm"}
                      color={"secondary"}>&nbsp;{List.id}&nbsp;</Chip>
              )
            case "createTime":
              return (
                <Chip color="secondary" variant="dot" size={"sm"}>{List.createTime}</Chip>
              )
            case "updateTime":
              return (
                <Chip color="danger" variant="dot" size={"sm"}>{List.updateTime}</Chip>
              )
            case "status":
              return (
                <Switch isSelected={List.type != 0} color="secondary" size={"sm"}
                        onValueChange={(isSelected) => {
                          setNoteId(List.id)
                          if (!isSelected) {
                            //选中
                            /*ToastUtil("请在分享中心关闭分享！", '🦉', "error");*/
                            ShareModifyService(List.shareId, 0, 0).then(r => {/*处理返回结果*/
                            })
                          } else {
                            //未选中
                            //判断是否已经在分享文档里
                            if (List.shareId === "0") {
                              //未分享过
                              onOpenShare()
                            } else {
                              //分享过
                              ShareModifyService(List.shareId, 1, 0).then(r => {/*处理返回结果*/
                              })
                            }
                          }
                        }} />
              )
            case "title":
              return (
                <h6 className={"truncate font-medium text-base"}>{List.title}</h6>
              )
            case "actions":
              return (
                <div className="relative flex justify-center items-end gap-2">
                  <Dropdown backdrop={"blur"} className="bg-background border-1 border-default-200">
                    <DropdownTrigger>
                      <Button isIconOnly radius="full" size="sm" variant="light">
                        <BiDotsVerticalRounded className="text-default-400" />
                      </Button>
                    </DropdownTrigger>
                    <DropdownMenu onAction={(key) => {
                      setDelData(key.toString())
                      onOpenDelNote()
                    }}
                    >
                      <DropdownItem color={"danger"} key={List.id}>删 除</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </div>
              )
            default:
              return cellValue
          }
        }
      }
      ,
      [onOpenDelFolder, onOpenDelNote, onOpenShare]
    )

  /*获取文件夹数据*/
  let listFolder = useAsyncList({
    async load({ signal }) {
      try {
        const path = search.get("path")
        const folderData = await FolderService(path === null ? "root" : path)
        if (folderData !== undefined && folderData !== null && folderData.status) {
          //setIsLoadingFolder(false);
          return {
            items: folderData.data
          }
        } else {
          return {
            items: []
          }
        }
      } catch (e) {
        throw new Error("出现未知错误，请刷新")
      }
    }
  })
  /*获取笔记数据*/
  let listNote = useAsyncList({
    async load({ signal }) {
      try {
        const path = search.get("path")
        const noteData = await NoteService(path === null ? "root" : path)
        if (noteData !== undefined && noteData !== null && noteData.status) {
          //setIsLoadingNote(false);
          return {
            items: noteData.data
          }
        } else {
          return {
            items: []
          }
        }
      } catch (e) {
        throw new Error("出现未知错误，请刷新")
      }
    }
  })
  /*目录/笔记状态定义*/
  /*const [folderData, setFolderData] = useState([]);
  const [noteData, setNoteData] = useState([]);*/
  /*第二种获取方式*/
  /*useEffect(() => {
      const fetchData = async () => {
          const [folderRes, noteRes] = await Promise.all([
              FolderService("root"),
              NoteService("root"),
          ]);
          setFolderData(folderRes.data);
          setNoteData(noteRes.data);
      }
      fetchData().then(r => {
      });
  }, []);*/

  //获取部分路径
  function getPathParts(path: string) {
    return path.split("/").filter(part => part) //将路径分割为部分并过滤掉空白部分
  }

  /*创建一个消息监听器，列表发生变化重新渲染.*/
  //文件夹
  PubSub.unsubscribe("refreshFolder")
  PubSub.subscribe("refreshFolder", (_, data) => {
    listFolder.reload()//重新加载
  })
  //笔记
  PubSub.unsubscribe("refreshNote")
  PubSub.subscribe("refreshNote", (_, data) => {
    listNote.reload()
  })


  /*第二种方式的更新检测状态*/
  useEffect(() => {
    async function fetchData() {
      /*更新路由栏路径*/
      const localUrl = search.get("path")
      if (localUrl === null || localUrl === "root" || localUrl === "/") {
        setPath(["/"])
      } else {
        const newPathList = [...path] //复制当前路径列表
        //查找新路径在当前路径列表中的位置
        const index = newPathList.indexOf(localUrl)
        if (index !== -1) {
          // 如果存在，则删除该路径后面的所有值
          newPathList.splice(index + 1, newPathList.length - index - 1)
        } else {
          //如果不存在，则将新路径合并到当前路径列表中
          newPathList.push(...getPathParts(localUrl))
        }
        /*更新路由*/
        setPath(newPathList)
      }
      //在path或location变化时重新加载数据  路径发生了变化
      listFolder.reload()
      listNote.reload()
      //更新加载中状态
      delay(() => {
        setIsLoadingNote(false)
        setIsLoadingFolder(false)
      }, 100)
    }

    fetchData().then(r => {
      /*执行fetchData时出错才执行*/
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location])

  /*渲染*/
  return List(listFolder, listNote)

  /*存在目录*/
  function List(listFolder: any, listNote: any) {
    return (
      <>
        <div className={"flex-col justify-center flex-grow items-start bg-white p-3 space-y-3"}>
          <Breadcrumbs key={"boy"} variant={"light"} color={"foreground"} size={"md"}
                       hideSeparator /*隐藏层级icon*/
                       classNames={{
                         list: "gap-3"
                       }}
                       itemClasses={{
                         item: [
                           "px-2 py-0.5 border-small border-default-400 rounded-small",
                           "data-[current=true]:border-default-800 data-[current=true]:bg-foreground data-[current=true]:text-background transition-colors",
                           "data-[disabled=true]:border-default-400 data-[disabled=true]:bg-default-100"
                         ]
                       }}
          >
            {
              path.map((segment, index) => (
                <BreadcrumbItem onPress={() => {
                  /*当前目录则无效果   相同不会更新 所以不用判断*/
                  /*if (segment === search.get('path')) {
                      return;
                  }*/
                  if (segment === "/") {
                    setPath(["/"])
                    setSearch("")
                    return
                  }
                  setSearch(`path=${segment}`)
                }} key={segment} startContent={segment === "/" ?
                  <AiFillHome /> : <BiFolderOpen />}>{segment}</BreadcrumbItem>
              ))
            }
          </Breadcrumbs>
          {/*目录渲染*/}
          {
            //加载中状态判断
            isLoadingFolder ?
              <Card className={"h-1/3"} shadow={"md"} radius={"lg"}>
                <CardBody>
                  <div className={"flex justify-center flex-grow items-center bg-white p-5"}>
                    <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                             size={"sm"} />
                  </div>
                </CardBody>
              </Card> :
              listFolder.items.length === 0 ?
                DontExitsFolder("暂无文件夹哦 🧐") :
                <Table
                  title={"我的文件夹"}
                  aria-label="我的所有文件夹."
                  shadow={"md"}/*阴影*/
                  hideHeader={false}/*隐藏头部*/
                  isStriped={false}/*条纹化*/
                  isHeaderSticky={true}/*头部阴影*/
                  topContent={
                    <div className={"flex justify-between items-center"}>
                      <Chip color="default" variant="light">我的目录 📂</Chip>
                      <Button className={"w-min"} color="primary" endContent={<BiPlus />}
                              onPress={
                                onOpenFolder
                              }>
                        新建文件夹
                      </Button>
                    </div>
                  }
                  onClick={() => {
                  }}
                  onRowAction={(key) => {
                    /*setPath(key) 我使用第二种方式*/
                    /*设置新的目录ID*/
                    setSearch(`path=${key}`)
                    /*const newPath = [...path, `${key}`];
                    setPath(newPath);*/
                    //更新加载中状态
                    setIsLoadingNote(true)
                    setIsLoadingFolder(true)
                  }
                  }/*获取key 这里是ID*/
                  fullWidth={true}
                >
                  <TableHeader>
                    <TableColumn align={"center"} key="num">
                      #
                    </TableColumn>
                    <TableColumn align={"center"} key="title">
                      目录名
                    </TableColumn>
                    <TableColumn align={"center"} key="content">
                      目录简介
                    </TableColumn>
                    <TableColumn align={"center"} key="createTime">
                      创建时间
                    </TableColumn>
                    <TableColumn align={"center"} key="id">
                      目录号
                    </TableColumn>
                    <TableColumn align={"center"} key="status">
                      分享状态
                    </TableColumn>
                    <TableColumn align={"center"} key="actions">
                      操作
                    </TableColumn>
                  </TableHeader>
                  {/*设置内容*/}
                  <TableBody
                    items={listFolder.items}
                    isLoading={isLoadingFolder}
                    loadingContent={<Spinner label="加载中..." />}
                  >
                    {(item: any) => (
                      <TableRow key={item.id} className={"h-24"}>
                        {(columnKey) =>
                          <TableCell>{renderCell(item, columnKey, true)}</TableCell>
                        }
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
          }
          {/*笔记渲染*/}
          {
            //加载中状态判断
            isLoadingNote ?
              <Card className={"h-1/3"} shadow={"md"} radius={"lg"}>
                <CardBody>
                  <div className={"flex justify-center flex-grow items-center bg-white p-5"}>
                    <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                             size={"sm"} />
                  </div>
                </CardBody>
              </Card> :
              listNote.items.length === 0 ?
                DontExitsNote("暂无笔记哦 🥸") :
                <Table
                  title={"我的云笔记"}
                  aria-label="我的所有云笔记." color={"primary"}
                  shadow={"md"}/*阴影*/
                  hideHeader={false}/*隐藏头部*/
                  isStriped={false}/*条纹化*/
                  isHeaderSticky={true}/*头部阴影*/
                  topContent={
                    <div className={"flex justify-between items-center"}>
                      <Chip color="default" variant="light">我的笔记 📚</Chip>
                      <Button className={"w-min"} color="secondary" endContent={<BiPlus />}
                              onPress={
                                onOpenNote
                              }>
                        新建云笔记
                      </Button>
                    </div>
                  }
                  onRowAction={(key) => {   /*打开阅读界面*/
                    setNoteId(key.toString())
                    onOpen()
                  }
                  }/*获取key 这里是ID*/
                  fullWidth={true}
                >
                  <TableHeader>
                    <TableColumn align={"center"} key="num">
                      #
                    </TableColumn>
                    <TableColumn align={"center"} key="title">
                      笔记名
                    </TableColumn>
                    <TableColumn align={"center"} key="createTime">
                      创建时间
                    </TableColumn>
                    <TableColumn align={"center"} key="updateTime">
                      修改时间
                    </TableColumn>
                    <TableColumn align={"center"} key="id">
                      笔记号
                    </TableColumn>
                    <TableColumn align={"center"} key="status">
                      分享状态
                    </TableColumn>
                    <TableColumn align={"center"} key="actions">
                      操作
                    </TableColumn>
                  </TableHeader>
                  {/*设置内容*/
                  }
                  <TableBody
                    items={listNote.items}
                    isLoading={isLoadingNote}
                    loadingContent={<Spinner label="加载中..." />}
                  >
                    {/*渲染list*/}
                    {(item: any) => (
                      <TableRow key={item.id} className={"h-24"}>
                        {(columnKey) =>
                          <TableCell>{renderCell(item, columnKey, false)}</TableCell>
                        }
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
          }
          {/*编辑器*/}
          <NoteEdit isOpen={isOpen} onOpenChange={onOpenChange} noteId={noteId}
                    folderId={search.get("path")} />
          {/*创建文件夹*/}
          <CreateFolder isOpenFolder={isOpenFolder} onOpenChangeFolder={onOpenChangeFolder}
                        parentId={search.get("path")} />
          {/*创建笔记*/}
          <CreateNote isOpenNote={isOpenNote} onOpenChangeNote={onOpenChangeNote}
                      folderId={search.get("path")} />
          {/*删除笔记*/}
          <DelNoteService isOpenDelNote={isOpenDelNote} onOpenChangeDelNote={onOpenChangeDelNote}
                          noteId={delData} />
          {/*删除文件夹*/}
          <DelFolderService isOpenDelFolder={isOpenDelFolder} onOpenChangeDelFolder={onOpenChangeDelFolder}
                            folderId={delData} />
          {/*创建分享*/}
          <CreateShareService isOpenShare={isOpenShare} onOpenChangeShare={onOpenChangeShare}
                              noteId={noteId} />
        </div>
      </>
    )
  }

  /*不存在的目录*/
  function DontExitsFolder(message: string) {
    return (
      <div>
        <Card className={"h-1/3"} shadow={"md"} radius={"lg"}>
          <CardBody>
            <div className={"flex justify-between items-center"}>
              <Chip color="default" variant="light">我的目录 📂</Chip>
              <Button className={"w-min"} color="primary" endContent={<BiPlus />}
                      onPress={
                        onOpenFolder
                      }>
                新建文件夹
              </Button>
            </div>
            <div className={"flex justify-center flex-grow items-center bg-white p-5"}>
              <Code color="warning"> {message} </Code>
            </div>
          </CardBody>
        </Card>
      </div>
    )
  }

  /*不存在的文件*/
  function DontExitsNote(message: string) {
    return (
      <div>
        <Card className={"h-1/3"} shadow={"md"} radius={"lg"}>
          <CardBody>
            <div className={"flex justify-between items-center"}>
              <Chip color="default" variant="light">我的笔记 📚</Chip>
              <Button className={"w-min"} color="secondary" endContent={<BiPlus />}
                      onPress={
                        onOpenNote
                      }>
                新建云笔记
              </Button>
            </div>
            <div className={"flex justify-center flex-grow items-center bg-white p-5"}>
              <Code color="warning"> {message} </Code>
            </div>
          </CardBody>
        </Card>
      </div>
    )
  }
}